﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ModularAndPlugin.Core;
using SailHero.Soft.FrameWork.IDomainRepositories.Contracts;
using SailHero.Soft.FrameWork.Models;
using UI.Web.MVC.Models;

namespace UI.Web.MVC.Controllers
{


    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        /// <summary>
        /// 数据操作接口
        /// </summary>
        [Import]
        public ISys_UserRepository sys_UserRepository { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user =
                    sys_UserRepository.FirstOrDefault(
                        itm => itm.ACCOUNT == model.UserName && itm.PASSWORD == model.Password);
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    Session["user"] = user;
                    return string.IsNullOrEmpty(returnUrl)
                               ? (ActionResult)RedirectToAction("Index", "Home")
                               : Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "用户名或者密码不正确.");
                    return View(model);
                }
            }
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session["user"] = null;
            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult RegisterAjax()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var user = new SYS_USER() { USERID = Guid.NewGuid().ToString("N"), ACCOUNT = model.UserName, PASSWORD = model.Password, EMAIL = model.Email };
                    sys_UserRepository.Add(user);
                    sys_UserRepository.UnitOfWork.SaveChanges();
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    Session["user"] = user;
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(MembershipCreateStatus.ProviderError));
                }

            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }
        [HttpPost]
        public ActionResult RegisterAjax(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var user = new SYS_USER() { USERID = Guid.NewGuid().ToString("N"), ACCOUNT = model.UserName, PASSWORD = model.Password, EMAIL = model.Email };
                    sys_UserRepository.Add(user);
                    sys_UserRepository.UnitOfWork.SaveChanges();
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    Session["user"] = user;
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(MembershipCreateStatus.ProviderError));
                }

            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }
        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
